﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Mall.Infrastructure.Enums
{
    /// <summary>
    /// 备注特性
    /// </summary>
    public class DescriptionAttribute : Attribute
    {
        private string m_remark;
        public DescriptionAttribute(string remark)
        {
            this.m_remark = remark;
        }
        /// <summary>
        /// 备注
        /// </summary>
        public string Remark
        {
            get { return m_remark; }
            set { m_remark = value; }
        }

        /// <summary>
        /// 获取枚举的备注信息
        /// </summary>
        /// <param name="val">枚举值</param>
        /// <returns></returns>
        public static string GetEnumRemark(Enum val)
        {
            Type type = val.GetType();
            FieldInfo fd = type.GetField(val.ToString());
            if (fd == null)
            {
                return string.Empty;
            }
            object[] attrs = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
            string name = string.Empty;
            foreach (DescriptionAttribute attr in attrs)
            {
                name = attr.Remark;
            }
            return name;
        }
    }

    /// <summary>
    /// 枚举扩展类
    /// </summary>
    public static class EnumExtension
    {
        /// <summary>
        /// 获取枚举的备注信息
        /// </summary>
        /// <param name="em"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum em)
        {
            Type type = em.GetType();
            FieldInfo fd = type.GetField(em.ToString());
            if (fd == null)
            {
                return string.Empty;
            }
            object[] attrs = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
            string name = string.Empty;
            foreach (DescriptionAttribute attr in attrs)
            {
                name = attr.Remark;
            }
            return name;
        }

        public static Dictionary<int, string> GetList<T>()
        {
            Dictionary<int, string> list = new Dictionary<int, string>();
            Type type = typeof(T);
            foreach (int myCode in Enum.GetValues(type))
            {
                string strName = GetDescription((Enum)Enum.ToObject(type, myCode));//获取名称
                list.Add(myCode, strName);
            }
            return list;

        }
    }
}
